const { app, BrowserWindow, ipcMain, Tray, Menu } = require('electron')
const path = require('path')

let mainWindow
let tray = null

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    minWidth: 800,
    minHeight: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      preload: path.join(__dirname, 'preload.js') // 可选
    }
  })
  mainWindow.loadURL('http://localhost:5173')
  mainWindow.on('closed', () => { mainWindow = null })
}

// 示例：打开独立窗口（插件市场/开发者页等可用）
function createSubWindow (url, title = '子窗口') {
  const win = new BrowserWindow({
    width: 600,
    height: 400,
    title,
    parent: mainWindow,
    modal: false,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  })
  win.loadURL(url)
  return win
}

app.whenReady().then(() => {
  createWindow()
  tray = new Tray(path.join(__dirname, 'icon.ico'))
  const contextMenu = Menu.buildFromTemplate([
    { label: '显示主界面', click: () => mainWindow.show() },
    { label: '退出', click: () => app.quit() }
  ])
  tray.setToolTip('Widget桌面平台')
  tray.setContextMenu(contextMenu)
  tray.on('double-click', () => mainWindow.show())
})

// 支持Mac平台Dock图标激活
app.on('activate', () => { if (mainWindow === null) createWindow() })

// 所有窗口关闭时退出（Mac除外）
app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit() })

// 监听前端请求新建窗口
ipcMain.on('open-subwindow', (event, { url, title }) => {
  createSubWindow(url, title)
})
